package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.Gravity;
import android.widget.*;
import android.widget.LinearLayout.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.view.*;
import java.net.*;
public class MainActivity extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		setTitle("SnowingDesktopControler");
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		Button sendbtn=(Button)findViewById(R.id.mainButton1);
		//log.setFocusable(false);
		sendbtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view)
				{
					EditText log=(EditText)findViewById(R.id.mainEditText3);
					EditText editText1=(EditText)findViewById(R.id.mainEditText1);
					EditText editText2=(EditText)findViewById(R.id.mainEditText4);
					EditText msg=(EditText)findViewById(R.id.mainEditText2);
					String ip=editText1.getText().toString();
					try{
					int port=Integer.parseInt(editText2.getText().toString());
					String response=sendMessage(ip,port,msg.getText().toString());
					log.append(response+"\n");
					}catch(Exception e){
						log.append(e.toString()+"\n");
					}
				}
			});

    }
	static String sendMessage(String ip, int port, String message)
	{
		try
		{
			Socket s = new Socket();
			SocketAddress addr=new InetSocketAddress(ip,port);
			s.connect(addr,3000);
			OutputStream os = s.getOutputStream();
			InputStream is = s.getInputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write(message);
			bw.flush();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String mess = br.readLine();
			//System.out.println("服务器："+mess);
			return mess;

		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
			return "请求错误:"+e.toString();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return "请求错误"+e.toString();
		}
	}
}